using Assets.Client.RunTime;
using DotNetty.Buffers;
using DotNetty.Transport.Channels;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

public class Client
{
    public static UdpClient UdpClient = new UdpClient();

    public static TcpClient TcpClient = new TcpClient();

    public static IChannel UdpChannel;

    public static IChannel TcpChannel;

    private static string tcpHost = "192.168.10.112";

    private static int tcpPort = 8000;

    private static string udpHost = "0.0.0.0";

    private static int udpPort = 9000;

    /// <summary>
    /// Udp 绑定端口
    /// </summary>
    public static int UdpPort { get => udpPort; set => udpPort = value; }

    /// <summary>
    /// Tcp 连接端口
    /// </summary>
    public static int TcpPort { get => tcpPort; set => tcpPort = value; }

    public enum Protocol
    {
        Tcp, Udp
    }

    /// <summary>
    /// 发起连接
    /// </summary>
    public static void Connect(Protocol protocol)
    {
        switch (protocol)
        {
            case Protocol.Udp:
                if (UdpChannel == null || !UdpClient.Connected)
                {
                    Task<IChannel> udpChannelThread = Task.Run(() => UdpClient.ConnectAsync(udpHost, udpPort));
                    UdpChannel = udpChannelThread.Result;
                }
                break;
            case Protocol.Tcp:
                if (TcpChannel == null || !TcpClient.Connected)
                {
                    Task<IChannel> tcpChannelThread = Task<IChannel>.Run(() => TcpClient.ConnectAsync(tcpHost, tcpPort));
                    TcpChannel = tcpChannelThread.Result;
                }
                break;
            default:
                break;
        }
    }

    /// <summary>
    /// 断开连接
    /// </summary>
    public static async void DisConnect() 
    {
        if (TcpClient.Connected)
        {
            await TcpClient.DisconnectAsync();
            Debug.Log("Tcp 连接已关闭");
        }
        if (UdpClient.Connected)
        {
            await UdpClient.DisconnectAsync();
            Debug.Log("Udp 连接已关闭");
        }
    }
}
